<template>
  <div id="houseCost" class="p-2 addListBox">
    <div v-if="routeType == 'add'" style="margin: 20px 10px;font-weight: 600;font-size: 26px;display:flex;align-items: center;">添加工资记录</div>
    <div v-else style="margin: 20px 10px;font-weight: 600;font-size: 26px;display:flex;align-items: center;">修改工资记录</div>
    <el-card shadow="never">
      <el-table v-loading="loading" :data="wagesInfoList">
        <el-table-column fixed align="center" width="130px">
          <template #header>
            <div>人员信息 <span style="color: #ff0000;">*</span></div>
          </template>
          <template #default="scope">
            <el-cascader
              v-model="scope.row.peopleInfoId"
              placeholder="请输入人员信息"
              :options="useCompany.companyRYList"
              filterable
              :props="{ value: 'id',label: 'name',children: 'children'}"
              :show-all-levels="false"
              @change="selectPeople($event,scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column fixed align="center" width="130px">
          <template #header>
            <div>薪资年月<span style="color: #ff0000;">*</span></div>
          </template>
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.salaryPaymentDate"
              @change="TimeChange(scope.row)"
              value-format="YYYY-MM"
              type="month"
              placeholder="请选择工资发放日期"
            />
          </template>
        </el-table-column>
        <el-table-column fixed label="岗位" align="center" prop="post" />
        <el-table-column label="基础工资" align="center" prop="basePay" />
        <el-table-column label="岗位津贴" align="center" prop="postAllowance" />
        <el-table-column label="其他津贴" align="center" prop="otherAllowance" />
        <el-table-column label="服装补贴" align="center" prop="clothingAllowance" />
        <el-table-column label="应发工资" align="center" prop="salaryPayable" />
        <el-table-column align="center" width="130px">
          <template #header>
            <div>加班费</div>
          </template>
          <template #default="scope">
            <el-input v-model="scope.row.overtimePay" type="number" placeholder="请输入加班费" @input="actualSalaryPaidChanged(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column align="center" width="130px">
          <template #header>
            <div>未满月工资扣除</div>
          </template>
          <template #default="scope">
            <el-input
              v-model="scope.row.deductWorkFullHoursPay"
              type="number"
              placeholder="请输入未满月工资扣除"
              @input="actualSalaryPaidChanged(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" width="130px">
          <template #header>
            <div>扣当月个人公积金</div>
          </template>
          <template #default="scope">
            <el-input
              v-model="scope.row.deductingDyPersonalProvidentFund"
              type="number"
              placeholder="请输入扣当月个人公积金"
              @input="actualSalaryPaidChanged(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" width="130px">
          <template #header>
            <div>补服装补贴</div>
          </template>
          <template #default="scope">
            <el-input
              v-model="scope.row.patchClothingSubsidy"
              type="number"
              placeholder="请输入补服装补贴"
              @input="actualSalaryPaidChanged(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" width="130px">
          <template #header>
            <div>其他扣除</div>
          </template>
          <template #default="scope">
            <el-input v-model="scope.row.otherDeduct" type="number" placeholder="请输入其他扣除" @input="actualSalaryPaidChanged(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column align="center" width="130px">
          <template #header>
            <div>月度优秀员工</div>
          </template>
          <template #default="scope">
            <el-input
              v-model="scope.row.monthlyOutstandingEmployee"
              type="number"
              placeholder="请输入月度优秀员工"
              @input="actualSalaryPaidChanged(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="工资实发数" align="center" prop="actualSalaryPaid" />

        <el-table-column align="center" width="130px">
          <template #header>
            <div>当月社保</div>
          </template>
          <template #default="scope">
            <el-input v-model="scope.row.dySocialSecurity" type="number" placeholder="请输入当月社保" @input="totalLaborCostsChanged(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column align="center" width="130px">
          <template #header>
            <div>当月单位公积金</div>
          </template>
          <template #default="scope">
            <el-input
              v-model="scope.row.dyUnitProvidentFund"
              type="number"
              placeholder="请输入当月单位公积金"
              @input="totalLaborCostsChanged(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" width="130px">
          <template #header>
            <div>下月雇主责任险</div>
          </template>
          <template #default="scope">
            <el-input
              v-model="scope.row.employerLiabilityInsurance"
              type="number"
              placeholder="请输入下月雇主责任险"
              @input="totalLaborCostsChanged(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" width="130px">
          <template #header>
            <div>劳务管理费</div>
          </template>
          <template #default="scope">
            <el-input
              v-model="scope.row.laborManagementFee"
              type="number"
              placeholder="请输入劳务管理费"
              @input="totalLaborCostsChanged(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="劳务费用合计" align="center" prop="totalLaborCosts" />

        <el-table-column align="center" width="130px">
          <template #header>
            <div>备注</div>
          </template>
          <template #default="scope">
            <el-input v-model="scope.row.remark" placeholder="请输入内容" />
          </template>
        </el-table-column>

        <!-- <el-table-column fixed="right" v-if="routeType == 'add'" label="操作" align="center" class-name="small-padding fixed-width" width="50px">
          <template #default="scope">
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="wagesInfoList = wagesInfoList.filter(item => item != scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column> -->
      </el-table>
    </el-card>
    <div style="display: flex;justify-content: center;margin-top: 20px;">
      <!-- <el-button v-if="routeType == 'add'" type="primary" icon="Plus" @click="addLine">追加一条</el-button> -->
      <el-button v-if="routeType == 'add'" type="success" icon="Position" @click="handleQuery">提交全部</el-button>
      <el-button v-else type="success" icon="Position" @click="handleQuery">提交修改</el-button>
      <el-button @click="goBack">返 回</el-button>
    </div>
  </div>
</template>

<script setup name="AssetCataAdd" lang="ts">
import { getLaborCostTotal, updateLaborCostTotal, addLaborCostTotal } from '@/api/business/wages';
import { LaborCostTotalVO, LaborCostTotalQuery, LaborCostTotalForm } from '@/api/business/wages/types';
import { getPeopleInfo } from '@/api/business/peopleInfo';
import useCompanyStore from '@/store/modules/company';
import { addDays } from 'date-fns';
import { array } from 'vue-types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const router = useRoute();
const routeType = ref('add');
const useCompany = useCompanyStore();
const loading = ref(false);
const buttonLoading = ref(false);

const wagesInfoList = ref<LaborCostTotalVO[]>([]);
const listItem = {
  laborCostTotalId: undefined,
  peopleInfoId: undefined,
  post: undefined,
  basePay: 0,
  postAllowance: 0,
  otherAllowance: 0,
  clothingAllowance: 0,
  salaryPayable: 0,
  overtimePay: 0,
  deductWorkFullHoursPay: 0,
  deductingDyPersonalProvidentFund: 0,
  patchClothingSubsidy: 0,
  otherDeduct: 0,
  monthlyOutstandingEmployee: 0,
  actualSalaryPaid: 0,
  dySocialSecurity: 0,
  dyUnitProvidentFund: 0,
  employerLiabilityInsurance: 0,
  laborManagementFee: 0,
  totalLaborCosts: 0,
  salaryPaymentDate: undefined,
  remark: undefined,
}

const initFormData: LaborCostTotalForm = {
  laborCostTotalId: undefined,
  peopleInfoId: undefined,
  post: undefined,
  overtimePay: undefined,
  basePay: undefined,
  postAllowance: undefined,
  otherAllowance: undefined,
  clothingAllowance: undefined,
  salaryPayable: undefined,
  deductWorkFullHoursPay: undefined,
  deductingDyPersonalProvidentFund: undefined,
  patchClothingSubsidy: undefined,
  otherDeduct: undefined,
  monthlyOutstandingEmployee: undefined,
  actualSalaryPaid: undefined,
  dySocialSecurity: undefined,
  dyUnitProvidentFund: undefined,
  employerLiabilityInsurance: undefined,
  laborManagementFee: undefined,
  totalLaborCosts: undefined,
  salaryPaymentDate: undefined,
  remark: undefined,
}
const data = reactive<PageData<LaborCostTotalForm, LaborCostTotalQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    laborCostTotalId: undefined,
    peopleInfoId: undefined,
    post: undefined,
    overtimePay: undefined,
    basePay: undefined,
    postAllowance: undefined,
    otherAllowance: undefined,
    clothingAllowance: undefined,
    salaryPayable: undefined,
    deductWorkFullHoursPay: undefined,
    deductingDyPersonalProvidentFund: undefined,
    patchClothingSubsidy: undefined,
    otherDeduct: undefined,
    monthlyOutstandingEmployee: undefined,
    actualSalaryPaid: undefined,
    dySocialSecurity: undefined,
    dyUnitProvidentFund: undefined,
    employerLiabilityInsurance: undefined,
    laborManagementFee: undefined,
    totalLaborCosts: undefined,
    salaryPaymentDate: undefined,
    remark: undefined,
    params: {
    }
  },rules: {}
});

const { queryParams, form, rules } = toRefs(data);

const selectPeople = async(id:string,row:any) => {
  const res = await getPeopleInfo(id[id.length - 1]);
  row.post = res.data.post
  row.basePay = res.data.basePay
  row.postAllowance = res.data.postAllowance
  row.otherAllowance = res.data.otherAllowance
  row.clothingAllowance = res.data.clothingAllowance
  row.salaryPayable = res.data.salaryPayable
  row.actualSalaryPaid = res.data.salaryPayable
  row.entryTime = res.data.entryTime
  row.resignationTime = res.data.resignationTime
  if(row.salaryPaymentDate) {
    let difference
    if (row.resignationTime) {
      let time1 = new Date(row.resignationTime).getTime()
      let time2 = new Date(row.salaryPaymentDate).getTime()
      difference = (time1 - time2)/ (1000 * 60 * 60 * 24);; // 差异以毫秒为单位
      if(difference<15) {
        row.employerLiabilityInsurance = 60
        row.laborManagementFee = 35
      }else {
        row.employerLiabilityInsurance = 60
        row.laborManagementFee = 70
      }
    }else {
      let time3 = new Date(row.entryTime)
      let time4 = new Date(row.salaryPaymentDate)
      time4.setMonth(time4.getMonth() + 1);
      difference = (time4.getTime() - time3.getTime())/ (1000 * 60 * 60 * 24);; // 差异以毫秒为单位
      if(difference<15) {
        row.employerLiabilityInsurance = 120
        row.laborManagementFee = 35
      }else if(difference>15&&difference<32){
        row.employerLiabilityInsurance = 120
        row.laborManagementFee = 70
      }else {
        row.employerLiabilityInsurance = 60
        row.laborManagementFee = 70
      }
    }
    // row.totalLaborCosts = res.data.salaryPayable*1 + row.employerLiabilityInsurance*1 + row.laborManagementFee*1
    actualSalaryPaidChanged(row)
  }
}

// 追加一条
const addLine = () => {
  wagesInfoList.value.push(JSON.parse(JSON.stringify(listItem)))
}

const hasNoEmptyValues = () => {
  let flag = true
  for(let i=0;i<wagesInfoList.value.length;i++) {
    if(routeType.value == 'edit') {
      if(wagesInfoList.value[i].peopleInfoId == '' || wagesInfoList.value[i].peopleInfoId == null){
        ElMessage.error('请将选择正确的人员信息！')
        return false
      }else if(wagesInfoList.value[i].salaryPaymentDate == '' || wagesInfoList.value[i].salaryPaymentDate == null) {
        ElMessage.error('请将选择薪资发放日期！')
        return false
      }
      if (i==wagesInfoList.value.length-1) {
        return true
      }
    }else {
      if(wagesInfoList.value[i].peopleInfoId == '' || wagesInfoList.value[i].peopleInfoId == null){
        ElMessage.error('请将选择正确的人员信息！')
        return false
      }else if(wagesInfoList.value[i].salaryPaymentDate == '' || wagesInfoList.value[i].salaryPaymentDate == null) {
        ElMessage.error('请将选择薪资发放日期！')
        return false
      }
      if (i==wagesInfoList.value.length-1) {
        return true
      }
    }
  }
  return flag
}

/** 返回 */
const goBack = () =>{
  const obj = { path: "/administration/wages" };
  proxy?.$tab.closeOpenPage(obj);
}

/** 提交按钮 */
const handleQuery = async () => {
  if(hasNoEmptyValues()) {
    if(routeType.value == 'edit') {
      wagesInfoList.value.forEach(item => {
        if(typeof(item.peopleInfoId) == 'object') {
          item.peopleInfoId = item.peopleInfoId[item.peopleInfoId.length-1]
        }
      })
      // await updateLaborCostTotal({'houseCostListBo':wagesInfoList.value}).then(() =>  {proxy?.$modal.msgSuccess("修改成功");});
      await updateLaborCostTotal(wagesInfoList.value[0]).then(() =>  {proxy?.$modal.msgSuccess("修改成功");});
      await goBack()
    }else {
      wagesInfoList.value.forEach(item => {
        item.peopleInfoId = item.peopleInfoId[item.peopleInfoId.length-1]
      })
      // await addLaborCostTotal({'houseCostListBo':wagesInfoList.value}).then((res) =>  {
        await addLaborCostTotal(wagesInfoList.value[0]).then((res) =>  {
        sessionStorage.setItem('houseCost','')
        proxy?.$modal.msgSuccess("新增成功");
      });
      await goBack()
    }
  }
}

const actualSalaryPaidChanged = (row:any) => {
  row.actualSalaryPaid = (row.salaryPayable*1 + row.overtimePay*1 - row.deductWorkFullHoursPay*1 - row.deductingDyPersonalProvidentFund*1 + row.patchClothingSubsidy*1 - row.otherDeduct*1 + row.monthlyOutstandingEmployee*1).toFixed(2)
  row.totalLaborCosts = (row.actualSalaryPaid*1 + row.dySocialSecurity*1 + row.dyUnitProvidentFund*1 + row.employerLiabilityInsurance*1 + row.laborManagementFee*1 - row.otherDeduct*1).toFixed(2)
}

const totalLaborCostsChanged = (row:any) => {
  row.totalLaborCosts = (row.actualSalaryPaid*1 + row.dySocialSecurity*1 + row.dyUnitProvidentFund*1 + row.employerLiabilityInsurance*1 + row.laborManagementFee*1 - row.otherDeduct*1).toFixed(2)
}

const TimeChange = (row:any) => {
  let difference
  if (row.resignationTime) {
    let time1 = new Date(row.resignationTime).getTime()
    let time2 = new Date(row.salaryPaymentDate).getTime()
    difference = (time1 - time2)/ (1000 * 60 * 60 * 24);; // 差异以毫秒为单位
    if(difference<15) {
      row.employerLiabilityInsurance = 60
      row.laborManagementFee = 35
    }else {
      row.employerLiabilityInsurance = 60
      row.laborManagementFee = 70
    }
  }else if(row.entryTime) {
    let time3 = new Date(row.entryTime)
    let time4 = new Date(row.salaryPaymentDate)
    time4.setMonth(time4.getMonth() + 1);
    difference = (time4.getTime() - time3.getTime())/ (1000 * 60 * 60 * 24);; // 差异以毫秒为单位
    if(difference<15) {
      row.employerLiabilityInsurance = 120
      row.laborManagementFee = 35
    }else if(difference>15&&difference<31){
      row.employerLiabilityInsurance = 120
      row.laborManagementFee = 70
    }else {
      row.employerLiabilityInsurance = 60
      row.laborManagementFee = 70
    }
  }
  // row.totalLaborCosts = row.salaryPayable*1 + row.employerLiabilityInsurance*1 + row.laborManagementFee*1
  actualSalaryPaidChanged(row)
}

onMounted(async () => {
  if(router.query.type == 'edit') {
    routeType.value = router.query.type
    getLaborCostTotal(router.query.id).then(res => {
      wagesInfoList.value = [res.data]
    })
  }else{
    addLine()
  }
})
</script>
<style>
.el-table .cell {
  padding: 0 4px;
}
.addListBox .el-date-editor  {
  --el-date-editor-width: 122px;
}
.error-row {
  background:rgba(255, 0, 0, .3) !important;
}
</style>
